package com.lotusfall.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static ObjectMapper mapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求方式（get/post/...）
        if(!StringUtils.equalsIgnoreCase(request.getMethod(),"get")){
            return true;
        }

        // 通过缓存做命中 请求的md5（url + 请求参数）
        String redisKey = createRedisKey(request);

        String data = this.stringRedisTemplate.opsForValue().get(redisKey);

        System.out.println(data);
        if(StringUtils.isEmpty(data)){
            // 未命中，放行
            return true;
        }
        // 命中，进行相应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(data);
        return false;
    }

    public static String createRedisKey(HttpServletRequest request) throws IOException {
        String paramStr = request.getRequestURI();
        Map<String ,String[]> parameterMap = request.getParameterMap();
        if (parameterMap.isEmpty()){
            paramStr += IOUtils.toString(request.getInputStream().toString().getBytes(),"UTF-8") ;
        }else {
            paramStr += mapper.writeValueAsString(request.getParameterMap());
        }
        String redisKey = "WEB_DATA" + DigestUtils.md5Hex(paramStr);
        return redisKey;
    }
}
